package com.wutongyu.mannyburger;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class ProductDetailActivity extends AppCompatActivity {

    private static final String TAG = "ProductDetailActivity";

    // 界面控件
    private ViewPager2 productImageSlider;
    private TabLayout imageSliderIndicator;
    private TextView productName;
    private TextView productCategory;
    private TextView productPrice;
    private TextView productDescription;
    private Button btnAddToCart;
    private Button btnBuyNow;
    private ImageButton btnDecrease;
    private ImageButton btnIncrease;
    private TextView productQuantity;
    private RecyclerView recyclerViewSpecs;
    private RecyclerView recyclerViewRelated;
    private RecyclerView recyclerViewComments;
    private TextView noCommentsText;
    private TextView viewAllComments;

    // 数据
    private Product product;
    private int quantity = 1;
    private ProductDatabaseHelper dbHelper;
    private CartManager cartManager;
    private List<Integer> productImages;
    private List<String> productSpecs;
    private List<Product> relatedProducts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);

        // 初始化工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("商品详情");

        // 获取传递过来的商品ID
        int productId = getIntent().getIntExtra("product_id", -1);
        if (productId == -1) {
            Toast.makeText(this, "商品信息获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化控件和数据
        initViews();
        initData(productId);
        setupListeners();
    }

    private void initViews() {
        productImageSlider = findViewById(R.id.product_image_slider);
        imageSliderIndicator = findViewById(R.id.image_slider_indicator);
        productName = findViewById(R.id.product_name);
        productCategory = findViewById(R.id.product_category);
        productPrice = findViewById(R.id.product_price);
        productDescription = findViewById(R.id.product_description);
        btnAddToCart = findViewById(R.id.btn_add_to_cart);
        btnBuyNow = findViewById(R.id.btn_buy_now);
        btnDecrease = findViewById(R.id.btn_decrease);
        btnIncrease = findViewById(R.id.btn_increase);
        productQuantity = findViewById(R.id.product_quantity);
        recyclerViewSpecs = findViewById(R.id.recycler_view_specs);
        recyclerViewRelated = findViewById(R.id.recycler_view_related);
        recyclerViewComments = findViewById(R.id.recycler_view_comments);
        noCommentsText = findViewById(R.id.no_comments);
        viewAllComments = findViewById(R.id.view_all_comments);
    }

    private void initData(int productId) {
        // 初始化数据库帮助类和购物车管理器
        dbHelper = new ProductDatabaseHelper(this);
        cartManager = CartManager.getInstance();
        cartManager.loadCart(this);

        // 从数据库加载商品信息
        product = loadProductById(productId);
        if (product == null) {
            Toast.makeText(this, "商品信息获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 显示商品信息
        displayProductInfo();

        // 初始化图片轮播
        setupImageSlider();

        // 初始化规格选择
        setupSpecsRecyclerView();

        // 加载相关商品
        loadRelatedProducts();

        // 加载评论
        loadComments();
    }

    private Product loadProductById(int productId) {
        List<Product> allProducts = dbHelper.getAllProducts();
        for (Product product : allProducts) {
            if (product.getId() == productId) {
                return product;
            }
        }
        return null;
    }

    private void displayProductInfo() {
        // 显示商品基本信息
        productName.setText(product.getName());
        productCategory.setText(product.getCategory());
        productPrice.setText("¥" + product.getPrice());
        productDescription.setText(product.getDescription());
    }

    private void setupImageSlider() {
        // 模拟图片集合（实际应用中应从数据库或服务器获取）
        productImages = new ArrayList<>();
        productImages.add(product.getImageResId()); // 主图
        
        // 添加额外的图片（这里使用同一张图片模拟多张效果）
        productImages.add(product.getImageResId());
        productImages.add(product.getImageResId());
        
        // 设置图片轮播适配器
        ImageSliderAdapter imageSliderAdapter = new ImageSliderAdapter(productImages);
        productImageSlider.setAdapter(imageSliderAdapter);
        
        // 设置指示器
        new TabLayoutMediator(imageSliderIndicator, productImageSlider,
                (tab, position) -> {
                    // 可以在这里设置TabLayout的内容，但因为我们只需要显示点，所以这里什么也不做
                }).attach();
    }

    private void setupSpecsRecyclerView() {
        // 模拟规格数据
        productSpecs = new ArrayList<>();
        
        // 根据产品类型添加不同规格
        if ("汉堡".equals(product.getCategory())) {
            productSpecs.add("标准");
            productSpecs.add("加量");
            productSpecs.add("减辣");
            productSpecs.add("去洋葱");
        } else if ("小吃".equals(product.getCategory())) {
            productSpecs.add("小份");
            productSpecs.add("中份");
            productSpecs.add("大份");
        } else if ("饮料".equals(product.getCategory())) {
            productSpecs.add("常温");
            productSpecs.add("加冰");
            productSpecs.add("少冰");
        } else {
            // 默认规格选项
            productSpecs.add("标准");
            productSpecs.add("定制");
        }
        
        // 设置规格选择适配器
        ProductSpecAdapter specAdapter = new ProductSpecAdapter(this, productSpecs);
        recyclerViewSpecs.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewSpecs.setAdapter(specAdapter);
    }

    private void loadRelatedProducts() {
        // 获取同类别的相关商品
        relatedProducts = dbHelper.getProductsByCategory(product.getCategory());
        
        // 移除当前商品
        List<Product> filteredRelatedProducts = new ArrayList<>();
        for (Product relatedProduct : relatedProducts) {
            if (relatedProduct.getId() != product.getId()) {
                filteredRelatedProducts.add(relatedProduct);
            }
        }
        
        // 设置相关商品适配器
        RelatedProductAdapter relatedProductAdapter = new RelatedProductAdapter(this, filteredRelatedProducts);
        recyclerViewRelated.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerViewRelated.setAdapter(relatedProductAdapter);
        
        // 设置相关商品点击事件
        relatedProductAdapter.setOnItemClickListener(position -> {
            Product clickedProduct = filteredRelatedProducts.get(position);
            Intent intent = new Intent(ProductDetailActivity.this, ProductDetailActivity.class);
            intent.putExtra("product_id", clickedProduct.getId());
            startActivity(intent);
        });
    }

    private void loadComments() {
        // 此处应从评论数据库加载评论
        // 目前显示"暂无评价"
        recyclerViewComments.setVisibility(View.GONE);
        noCommentsText.setVisibility(View.VISIBLE);
        
        // 查看全部评价按钮点击事件
        viewAllComments.setOnClickListener(v -> {
            Intent intent = new Intent(ProductDetailActivity.this, CommentActivity.class);
            intent.putExtra("product_id", product.getId());
            startActivity(intent);
        });
    }

    private void setupListeners() {
        // 数量增减按钮
        btnDecrease.setOnClickListener(v -> {
            if (quantity > 1) {
                quantity--;
                productQuantity.setText(String.valueOf(quantity));
            }
        });
        
        btnIncrease.setOnClickListener(v -> {
            quantity++;
            productQuantity.setText(String.valueOf(quantity));
        });
        
        // 加入购物车按钮
        btnAddToCart.setOnClickListener(v -> {
            product.setQuantity(quantity);
            cartManager.addToCart(product);
            cartManager.saveCart(this);
            Toast.makeText(this, "已加入购物车", Toast.LENGTH_SHORT).show();
        });
        
        // 立即购买按钮
        btnBuyNow.setOnClickListener(v -> {
            product.setQuantity(quantity);
            cartManager.clearCart();
            cartManager.addToCart(product);
            cartManager.saveCart(this);
            
            // 组装订单信息
            StringBuilder orderDetails = new StringBuilder();
            orderDetails.append(product.getName())
                .append(" x").append(quantity)
                .append(" - ¥").append(String.format("%.2f", product.getPrice() * quantity));
            
            // 跳转到结算页面
            Intent intent = new Intent(ProductDetailActivity.this, OrderActivity.class);
            intent.putExtra("order_details", orderDetails.toString());
            intent.putExtra("total_price", product.getPrice() * quantity);
            startActivity(intent);
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 